#include "cs104_server.h"


#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>

#include <QMutexLocker>


void
printCP56Time2a(CP56Time2a time)
{
    printf("%02i:%02i:%02i %02i/%02i/%04i", CP56Time2a_getHour(time),
        CP56Time2a_getMinute(time),
        CP56Time2a_getSecond(time),
        CP56Time2a_getDayOfMonth(time),
        CP56Time2a_getMonth(time),
        CP56Time2a_getYear(time) + 2000);
}

/* Callback handler to log sent or received messages (optional) */
static void
rawMessageHandler(void* parameter, IMasterConnection conneciton, uint8_t* msg, int msgSize, bool sent)
{
    if (sent)
        printf("SEND: ");
    else
        printf("RCVD: ");

    int i;
    for (i = 0; i < msgSize; i++) {
        printf("%02x ", msg[i]);
    }

    printf("\n");
}

static bool
clockSyncHandler(void* parameter, IMasterConnection connection, CS101_ASDU asdu, CP56Time2a newTime)
{
    printf("Process time sync command with time "); printCP56Time2a(newTime); printf("\n");

    uint64_t newSystemTimeInMs = CP56Time2a_toMsTimestamp(newTime);

    /* Set time for ACT_CON message */
    CP56Time2a_setFromMsTimestamp(newTime, Hal_getTimeInMs());

    /* update system time here */

    return true;
}

static bool
interrogationHandler(void* parameter, IMasterConnection connection, CS101_ASDU asdu, uint8_t qoi)
{
    printf("Received interrogation for group %i\n", qoi);
    simple_server* s = static_cast<simple_server*>(parameter);


    if (qoi == CS101_COT_INTERROGATED_BY_STATION) { /* only handle station interrogation */


        CS101_AppLayerParameters alParams = IMasterConnection_getApplicationLayerParameters(connection);
        IMasterConnection_sendACT_CON(connection, asdu, false);

        /* The CS101 specification only allows information objects without timestamp in GI responses */

        // yc

        if (s->yc()->size() > 0)
        {

            CS101_ASDU newAsdu = CS101_ASDU_create(alParams, true, CS101_COT_INTERROGATED_BY_STATION,
                0, 1, false, false);
            //0x4001

            int yc_addr = 0x4001;
            InformationObject io = (InformationObject)MeasuredValueScaled_create(NULL, yc_addr++, s->yc()->at(0).value, s->yc()->at(0).qc);
            CS101_ASDU_addInformationObject(newAsdu, io);
            for (int i = 1; i < s->yc()->size(); i++)
            {
                CS101_ASDU_addInformationObject(newAsdu, (InformationObject)MeasuredValueScaled_create((MeasuredValueScaled)io, yc_addr++, s->yc()->at(i).value, s->yc()->at(i).qc));
            }

            InformationObject_destroy(io);
            IMasterConnection_sendASDU(connection, newAsdu);
            CS101_ASDU_destroy(newAsdu);
        }

        //yx
        if (s->yx()->size() > 0)
        {
            int yx_addr = 0x01;
            CS101_ASDU newAsdu = CS101_ASDU_create(alParams, true, CS101_COT_INTERROGATED_BY_STATION, 0, 1, false, false);
            InformationObject io = (InformationObject)SinglePointInformation_create(NULL, yx_addr++, s->yx()->at(0).statu, s->yx()->at(0).qc);
            CS101_ASDU_addInformationObject(newAsdu, io);
            for (int i = 1; i < s->yc()->size(); i++)
            {
                CS101_ASDU_addInformationObject(newAsdu, (InformationObject)SinglePointInformation_create(NULL, yx_addr++, s->yx()->at(i).statu, s->yx()->at(i).qc));
            }

            InformationObject_destroy(io);
            IMasterConnection_sendASDU(connection, newAsdu);
            CS101_ASDU_destroy(newAsdu);
        }
        //IMasterConnection_sendACT_TERM(connection, asdu);
    }
    else {
        IMasterConnection_sendACT_CON(connection, asdu, true);
    }

    return true;
}

static bool
asduHandler(void* parameter, IMasterConnection connection, CS101_ASDU asdu)
{
    if (CS101_ASDU_getTypeID(asdu) == C_SC_NA_1) {
        printf("received single command\n");

        if (CS101_ASDU_getCOT(asdu) == CS101_COT_ACTIVATION) {
            InformationObject io = CS101_ASDU_getElement(asdu, 0);

            if (io) {
                if (InformationObject_getObjectAddress(io) == 5000) {
                    SingleCommand sc = (SingleCommand)io;

                    printf("IOA: %i switch to %i\n", InformationObject_getObjectAddress(io),
                        SingleCommand_getState(sc));

                    CS101_ASDU_setCOT(asdu, CS101_COT_ACTIVATION_CON);
                }
                else
                    CS101_ASDU_setCOT(asdu, CS101_COT_UNKNOWN_IOA);

                InformationObject_destroy(io);
            }
            else {
                printf("ERROR: message has no valid information object\n");
                return true;
            }
        }
        else
            CS101_ASDU_setCOT(asdu, CS101_COT_UNKNOWN_COT);

        IMasterConnection_sendASDU(connection, asdu);

        return true;
    }

    return false;
}

static bool
connectionRequestHandler(void* parameter, const char* ipAddress)
{
    printf("New connection request from %s\n", ipAddress);

#if 0
    if (strcmp(ipAddress, "127.0.0.1") == 0) {
        printf("Accept connection\n");
        return true;
    }
    else {
        printf("Deny connection\n");
        return false;
    }
#else
    return true;
#endif
}

static void
connectionEventHandler(void* parameter, IMasterConnection con, CS104_PeerConnectionEvent event)
{
    simple_server* s = static_cast<simple_server*>(parameter);
    if (event == CS104_CON_EVENT_CONNECTION_OPENED) {
        printf("Connection opened (%p)\n", con);
        s->setConnected(true);
        s->setActivated(false);
    }
    else if (event == CS104_CON_EVENT_CONNECTION_CLOSED) {
        printf("Connection closed (%p)\n", con);
        s->setConnected(false);
        s->setActivated(false);
    }
    else if (event == CS104_CON_EVENT_ACTIVATED) {
        printf("Connection activated (%p)\n", con);
        s->setActivated(true);
    }
    else if (event == CS104_CON_EVENT_DEACTIVATED) {
        printf("Connection deactivated (%p)\n", con);
        s->setActivated(false);
    }
}




void simple_server::sendYC()
{
    std::vector<S_Yc> ycs;

    {
        QMutexLocker locker(&m_mutex);

        if (m_yc_change.size() == 0)
            return;

        ycs = m_yc_change;
    }





        CS101_ASDU newAsdu = CS101_ASDU_create(alParams, true, CS101_COT_INTERROGATED_BY_STATION,
            0, 1, false, false);

        InformationObject io = (InformationObject)MeasuredValueScaled_create(NULL, yc_addr++, s->yc()->at(0).value, s->yc()->at(0).qc);
        CS101_ASDU_addInformationObject(newAsdu, io);
        for (int i = 1; i < s->yc()->size(); i++)
        {
            CS101_ASDU_addInformationObject(newAsdu, (InformationObject)MeasuredValueScaled_create((MeasuredValueScaled)io, yc_addr++, s->yc()->at(i).value, s->yc()->at(i).qc));
        }

        InformationObject_destroy(io);
        IMasterConnection_sendASDU(connection, newAsdu);
        CS101_ASDU_destroy(newAsdu);
 
    //yx
    if (s->yx()->size() > 0)
    {
        int yx_addr = 0x01;
        CS101_ASDU newAsdu = CS101_ASDU_create(alParams, true, CS101_COT_INTERROGATED_BY_STATION, 0, 1, false, false);
        InformationObject io = (InformationObject)SinglePointInformation_create(NULL, yx_addr++, s->yx()->at(0).statu, s->yx()->at(0).qc);
        CS101_ASDU_addInformationObject(newAsdu, io);
        for (int i = 1; i < s->yc()->size(); i++)
        {
            CS101_ASDU_addInformationObject(newAsdu, (InformationObject)SinglePointInformation_create(NULL, yx_addr++, s->yx()->at(i).statu, s->yx()->at(i).qc));
        }

        InformationObject_destroy(io);
        IMasterConnection_sendASDU(connection, newAsdu);
        CS101_ASDU_destroy(newAsdu);
    }

}

simple_server::simple_server(const char* addr, int port):running(false),connected(false), activated(false)
{
    /* create a new slave/server instance with default connection parameters and
    * default message queue size */
    slave = CS104_Slave_create(10, 10);

    CS104_Slave_setLocalAddress(slave, "0.0.0.0");
    CS104_Slave_setLocalPort(slave, port);

    /* Set mode to a single redundancy group
    * NOTE: library has to be compiled with CONFIG_CS104_SUPPORT_SERVER_MODE_SINGLE_REDUNDANCY_GROUP enabled (=1)
    */
    CS104_Slave_setServerMode(slave, CS104_MODE_SINGLE_REDUNDANCY_GROUP);

    /* get the connection parameters - we need them to create correct ASDUs -
     * you can also modify the parameters here when default parameters are not to be used */
    alParams = CS104_Slave_getAppLayerParameters(slave);

    /* when you have to tweak the APCI parameters (t0-t3, k, w) you can access them here */
    apciParams = CS104_Slave_getConnectionParameters(slave);

    printf("APCI parameters:\n");
    printf("  t0: %i\n", apciParams->t0);
    printf("  t1: %i\n", apciParams->t1);
    printf("  t2: %i\n", apciParams->t2);
    printf("  t3: %i\n", apciParams->t3);
    printf("  k: %i\n", apciParams->k);
    printf("  w: %i\n", apciParams->w);
}

simple_server::~simple_server()
{
    CS104_Slave_destroy(slave);
}

void simple_server::start()
{
    CS104_Slave_start(slave);

    if (CS104_Slave_isRunning(slave) == false) {
        printf("Starting server failed!\n");
        return;
    }

    running = true;

    int16_t scaledValue = 0;


    while (running) {


        Thread_sleep(1000);
    }

    CS104_Slave_stop(slave);
}

void simple_server::stop()
{
    running = false;
}

int simple_server::sendYC(int addr, float scaledValue, int qc)
{
    CS101_ASDU newAsdu = CS101_ASDU_create(alParams, false, CS101_COT_SPONTANEOUS, 0, 1, false, false);

    InformationObject io = (InformationObject)MeasuredValueScaled_create(NULL, addr, scaledValue, qc);

    CS101_ASDU_addInformationObject(newAsdu, io);

    InformationObject_destroy(io);

    /* Add ASDU to slave event queue */
    CS104_Slave_enqueueASDU(slave, newAsdu);

    CS101_ASDU_destroy(newAsdu);

    return 0;
}

int simple_server::sendYXDouble(int addr, int statu, int qc)
{
    CS101_ASDU newAsdu = CS101_ASDU_create(alParams, false, CS101_COT_SPONTANEOUS, 0, 1, false, false);

    InformationObject io = (InformationObject)DoublePointInformation_create(NULL, addr, (DoublePointValue)statu, qc);

    CS101_ASDU_addInformationObject(newAsdu, io);

    InformationObject_destroy(io);

    /* Add ASDU to slave event queue */
    CS104_Slave_enqueueASDU(slave, newAsdu);

    CS101_ASDU_destroy(newAsdu);

    return 0;
}

int simple_server::sendYXSingle(int addr, int statu, int qc)
{
    CS101_ASDU newAsdu = CS101_ASDU_create(alParams, false, CS101_COT_SPONTANEOUS, 0, 1, false, false);

    InformationObject io = (InformationObject)SinglePointInformation_create(NULL, addr, statu, qc);

    CS101_ASDU_addInformationObject(newAsdu, io);

    InformationObject_destroy(io);

    /* Add ASDU to slave event queue */
    CS104_Slave_enqueueASDU(slave, newAsdu);

    CS101_ASDU_destroy(newAsdu);

    return 0;
}

void simple_server::initHandle()
{
    /* set the callback handler for the clock synchronization command */
    CS104_Slave_setClockSyncHandler(slave, clockSyncHandler, this);

    /* set the callback handler for the interrogation command */
    CS104_Slave_setInterrogationHandler(slave, interrogationHandler, this);

    /* set handler for other message types */
    CS104_Slave_setASDUHandler(slave, asduHandler, this);

    /* set handler to handle connection requests (optional) */
    CS104_Slave_setConnectionRequestHandler(slave, connectionRequestHandler, this);

    /* set handler to track connection events (optional) */
    CS104_Slave_setConnectionEventHandler(slave, connectionEventHandler, this);

    /* uncomment to log messages */
    CS104_Slave_setRawMessageHandler(slave, rawMessageHandler, NULL);
}